﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MetalSoda
{
    public sealed class EndPointObject
    {
        internal readonly ServiceHost Host;
        internal readonly Service Service;

        internal EndPointObject(ServiceHost host, Service service)
        {
            this.Host = host;
            this.Service = service;
        }

        public override string ToString()
        {
            return string.Format("{0}/{1}", this.Host.Name, this.Service.Name);
        }

        public EndPointObject BindToSelf() { return BindTo(this); }

        public EndPointObject BindTo(EndPointObject other, Func<Route, bool> routeConfig = null)
        {
            if (other == null) { throw new ArgumentNullException("other"); }
            if (false == this.Service.Contracts.Intersect(other.Service.Contracts).Any())
            {
                throw new InvalidOperationException();
            }

            routeConfig = routeConfig ?? ((route) => true);
            if (Host.AddEndpoint(other))
            {
                // Creates and register routes to the other side
                foreach (var farDatabase in other.Host.Databases)
                {
                    var routes = new RouteCollection(localHost: this.Host, farHost: other.Host, farService: other.Service, policies: null);
                    this.Host.RegisterRoutes(routes);
                }
                other.BindTo(this);
            }
            return this;
        }
    }
}
